const {
	domain,
	isDebug
} = require('@/config')

const mockXHR = require('../mock/base/index.js')

// 当为debug模式时，会启用mock
if (isDebug) mockXHR(domain)

const request = function({
	url,
	method = 'GET',
	data,
	showLoading = false,
	showError = false
}) {

	if (!url) throw new Error('url地址不存在，请正确填写url地址!')

	const originUrl = url;

	if (domain && url.indexOf("://") == -1) url = `${domain}${url}`

	try {
		if (showLoading) {
			uni.showLoading({
				title: '加载中',
				mask: true, //防止触摸穿透
			});
		}
	} catch (e) {}

	return new Promise((resolve, reject) => {

		uni.request({
			url,
			data,
			method,
			success: (res) => {
				resolve(res.data)
			},
			fail: (res) => {
				resolve(res)
				if (showError) {
					const checkType = Object.prototype.toString.call(showError);
					uni.showModal({
						title: '提示',
						content: (checkType === '[object String]') ? showError :
							'网络有些波动，请稍后再试',
						showCancel: false
					})
				}
				console.error(`接口异常，错误信息: ${JSON.stringify(res)}`)
			},
			complete: _ => {
				if (showLoading) uni.hideLoading();
				uni.$emit('ajaxComplete', originUrl)
			}
		})

	})
}

module.exports = request
